package com.epfresh.supplier.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.SoftKeyBoardListener;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MultipleStatusView;
import com.epfresh.api.widget.keyboard.KeyboardUtil;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.pickerview.dialog.ValiditypriceDialog;
import com.epfresh.supplier.R;
import com.epfresh.supplier.adapter.JoinPriceGoodsListViewBinder;
import com.epfresh.supplier.dialog.CustomDetailDeleteDialog;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.JoinStoreListBean;
import com.epfresh.supplier.entity.StatusEntity;
import com.epfresh.supplier.widget.WrapContentLinearLayoutManager;
import com.google.gson.Gson;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;

/*联营报价*/
public class JoinPriceActivity extends BaseActivity {
    private View ll_tips;
    private ImageView img_dismiss;
    private MultipleStatusView msvGoods;
    RecyclerView rvGoods;
    MultiTypeAdapter mGoodsAdapter;
    JoinPriceGoodsListViewBinder mGoodsBinder;
    //LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();
    List<JoinStoreListBean.ProductInfoBean> mGoods = new ArrayList<>();

    JoinStoreListBean currentStore;
    JoinStoreListBean.ProductInfoBean currentGoods;
    int pageNum = 0;
    private PtrFrameLayout ptrFrameLayout;
    boolean freshFlag = false;
    private boolean isClickLoad = true;
    private boolean noJoinFlag = false;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rvGoods, header) /*&& !loadMoreDelegate.isLoading()*/;
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            freshFlag = true;
            reqGoodsList(0);
        }
    };
    private ValiditypriceDialog validitypriceDialog;
    private List<String> expireTime = new ArrayList<>();
    /*    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing();
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();

            reqGoodsList(pageNum + 1);
        }
    };*/

    private void initHeadView() {
        ptrFrameLayout = (PtrFrameLayout) findViewById(R.id.ptr_ff);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    protected View getToolBarView() {
        View view = inflaterView(R.layout.toolbar_change_price, null);
        return view;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join_goods);

        toolbarTitle.setText("联营报价");
        ivBack.setVisibility(View.VISIBLE);
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setText("提交");
        rightbtn.setTextColor(0xff626262);
        rightbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mGoods.size(); i++) {
                    if (!mGoods.get(i).isJointEnabled()) {
                        noJoinFlag = true;
                    }
                }
                if (noJoinFlag) {
                    for (int i = 0; i < mGoods.size(); i++) {
                        if (mGoods.get(i).getPriceNow() == 0) {
                            toast("商品销售价不能为0");
                            return;
                        }
                    }
                    if (null != expireTime && expireTime.size() != 0) {
                        if (validitypriceDialog == null) {
                            validitypriceDialog = new ValiditypriceDialog(JoinPriceActivity.this, expireTime);
                        }
                        validitypriceDialog.setSelectedPositionAdapter(-1);
                        validitypriceDialog.setOkListener(new ValiditypriceDialog.ClickOkListener() {
                            @Override
                            public void clickOk() {
                                if (validitypriceDialog.getAdapter() != null) {
                                    if (validitypriceDialog.getAdapter().getSelectedPosition() != -1) {
                                        validitypriceDialog.dismiss();
                                        submit(validitypriceDialog.getAdapter().getSelectedPosition());
                                    } else {
                                        Toast.makeText(mContext, "请选择商品价格有效期", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }

                            @Override
                            public void clickcancle() {

                            }
                        });
                        validitypriceDialog.show();
                    }
                } else {
                    submit(0);
                }

            }
        });
        //初始化view
        initView();
        reqGoodsList(0);
    }

    private void initView() {

        ll_tips = findViewById(R.id.ll_tips);
        img_dismiss = findViewById(R.id.img_dismiss);
        img_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ll_tips.getVisibility() == View.VISIBLE) {
                    isClickLoad = false;
                    ll_tips.setVisibility(View.GONE);
                }
            }
        });
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);
        msvGoods.setHint("无联营商品");
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        msvGoods.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqGoodsList(0);
            }
        });

        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                mGoodsBinder.setKeyboardShow(true);
            }

            @Override
            public void keyBoardHide(int height) {
                mGoodsBinder.setKeyboardShow(false);
            }
        });

        initGoodsView();
    }

    private BigDecimal getUnit(JoinStoreListBean.ProductInfoBean goods) {
        BigDecimal unit;
        if (goods.getPrice() * 10 % 1 > 0) {
            unit = new BigDecimal(0.01);
        } else if (goods.getPrice() * 10 % 10 > 0) {
            unit = new BigDecimal(0.1);
        } else {
            unit = new BigDecimal(1);
        }
        return unit;
    }

    LinearLayoutManager layoutManagerGoods;

    private void initGoodsView() {
        initHeadView();
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        layoutManagerGoods = new WrapContentLinearLayoutManager(this);
        layoutManagerGoods.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(layoutManagerGoods);
        mGoodsAdapter = new MultiTypeAdapter();
        mGoodsBinder = new JoinPriceGoodsListViewBinder();
        mGoodsBinder.setOnTextChangerListener(new JoinPriceGoodsListViewBinder.OnTextChangerListener() {
            @Override
            public void onChange() {
                //updateCnt();/*刷新提示数据*/
            }
        });
        mGoodsBinder.setOnGroupListener(new JoinPriceGoodsListViewBinder.OnGroupListener() {
            @Override
            public void onGroup(int position, JoinStoreListBean goods) {
                //intoGroup(position,goods);
            }
        });
        mGoodsBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data instanceof JoinStoreListBean.ProductInfoBean) {
                    JoinStoreListBean.ProductInfoBean goods = ((JoinStoreListBean.ProductInfoBean) data);
                    BigDecimal unit = getUnit(goods);
//                    if(goods.getPriceNow()==null)
//                        goods.setPriceNow(goods.getPriceOnly());
                    if (view.getId() == R.id.iv_add) {
                        goods.setPriceNow(unit.add(new BigDecimal(goods.getPriceNow())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                        if (goods.getPriceNow() > 99999.99) {
                            toast("价格不能大于99999.99");
                            goods.setPriceNow(99999.99);
                        }
                    } else {
                        if ((new BigDecimal(goods.getPriceNow()).subtract(unit)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() <= 0) {
                            toast("价格不能小于0");
                            return;
                        }
                        goods.setPriceNow((new BigDecimal(goods.getPriceNow()).subtract(unit)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }
                    mGoodsAdapter.notifyDataSetChanged();
                }
            }
        });

        // LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
//        loadMoreViewBinder.setPaddingBottom(LocalDisplay.dp2px(65.5f));
        mGoodsAdapter.register(JoinStoreListBean.ProductInfoBean.class, mGoodsBinder);
        //mGoodsAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rvGoods.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setItems(mGoods);

        //loadMoreDelegate.attach(rvGoods, loadMoreSubject);
    }

    protected void updateGoodsList(ContentEntity<JoinStoreListBean> ce, Object tag) {
        int number = ce.getNumber();
        boolean last = ce.getLast();

        List<JoinStoreListBean> goodsItems = ce.getContent();

        pageNum = number;
        if (number == 0) {
            mGoods.clear();
        }
        for (int i = 0; i < goodsItems.size(); i++) {
            JoinStoreListBean bean = goodsItems.get(i);
            if (bean.isUpdatePriceAuth())
                rightbtn.setVisibility(View.VISIBLE);
            for (int j = 0; j < bean.getProduct().size(); j++) {
                bean.getProduct().get(j).setCenterName(bean.getCenterName());
                bean.getProduct().get(j).setUpdatePriceAuth(bean.isUpdatePriceAuth());
                bean.getProduct().get(j).setCnt(bean.getCnt());

                JoinStoreListBean.ProductInfoBean productInfoBean = bean.getProduct().get(j);
                productInfoBean.setShow(true);
                if (j == 0) {
                    bean.getProduct().get(j).setHeader(true);
                }
                if (j == bean.getProduct().size() - 1) {
                    bean.getProduct().get(j).setFooter(true);
                }
            }
            mGoods.addAll(bean.getProduct());
//            if(i==0){
//                bean.setHeader(true);
//            }
//            if(i==goodsItems.size()-1)
//                bean.setFooter(true);
//            if(i>0){
//                if(!bean.getCenterId().equals(goodsItems.get(i-1).getCenterId())){
//                    bean.setHeader(true);
//                }
//            }
//            if(i<goodsItems.size()-1){
//                if(!bean.getCenterId().equals(goodsItems.get(i+1).getCenterId())){
//                    bean.setFooter(true);
//                }
//            }
//            if(i==goodsItems.size()-1){
//                bean.setFooter(false);
//            }

        }

        if (goodsItems.size() > 0) {
//            mGoods.addAll(goodsItems);
            //loadMoreDelegate.addAllItem(items, goodsItems);
            //最后一个
            if (last) {
                //loadMoreDelegate.setStatusNoMore();
            } else {
                //loadMoreDelegate.setStatusNormal();
            }
            loadGoodsContent();
            mGoodsAdapter.notifyDataSetChanged();
        } else {//没有数据
            loadGoodsEmpty();
        }
    }

    protected void loadGoodsError() {
        if (mGoods.size() == 0)
            msvGoods.showError();
    }

    protected void loadGoodsEmpty() {
        rightbtn.setVisibility(View.GONE);
        msvGoods.showEmpty();
    }

    protected void showGoodsLoading() {
        if (mGoods.size() == 0) {
            msvGoods.showLoading();
        } else {
            msvGoods.showContent();
        }
    }

    protected void loadGoodsContent() {

        msvGoods.showContent();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    private void reqGoodsList(int pageNumber) {

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_joint_list);

        RequestEntityMapSupply.putParameter("storeId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNumber);
        RequestEntityMapSupply.putParameter("pageSize", 10);
        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_joint_list, onGoodsRequestListener);
    }

    private OnRequestListener<ContentEntity<JoinStoreListBean>> onGoodsRequestListener = new OnRequestListener<ContentEntity<JoinStoreListBean>>() {
        @Override
        public ContentEntity<JoinStoreListBean> jsonToObj(String responseStr) {

            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, JoinStoreListBean.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

            ptrFrameLayout.refreshComplete();

            loadGoodsError();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            loadGoodsError();
        }

        @Override
        public void onStart(Object tag) {
            if (freshFlag) {
                showGoodsLoading();
            } else {
                showProgressDialog();
                showGoodsLoading();
            }
            freshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<JoinStoreListBean>> response, Object tag) {
            hideProgressDialog();
            ptrFrameLayout.refreshComplete();
            if (response != null) {
                ContentEntity<JoinStoreListBean> responseElement = response.getResponseElement();
                expireTime.clear();
                if (null != responseElement.getExpireTime()) {
                    expireTime.addAll(responseElement.getExpireTime());
                }
                rightbtn.setVisibility(View.VISIBLE);
                //当点击关闭,就不会显示了更新数据
                if (isClickLoad) {
                    if (responseElement.isUpdate()) {
                        ll_tips.setVisibility(View.VISIBLE);
                    } else {
                        ll_tips.setVisibility(View.GONE);
                    }
                }
                noJoinFlag=false;
                updateGoodsList(responseElement, tag);
                if (validitypriceDialog != null) {
                    validitypriceDialog.setDataupdate(expireTime);
                }
            }
        }
    };

    class PriceModel {
        String id;
        String price;

        public PriceModel(String id, String price) {
            this.id = id;
            this.price = price;
        }
    }

    private void submit(int selectorposition) {
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(AppSupplyRouterConstant.cmd_store_product_joint_updatePrice);
        //RequestEntityMapSupply.putParameter("storeId",BaseApplication.getInstance().getStoreId());
        ArrayList list = new ArrayList();
        for (int i = 0; i < mGoods.size(); i++) {
            if (mGoods.get(i).getPriceNow() == 0) {
                toast("商品销售价不能为0");
                return;
            }
            String[] goods = new String[]{mGoods.get(i).getJoinId(), "" + mGoods.get(i).getPriceNow()};
            list.add(goods);
//            if (mGoods.get(i).getPrice() != mGoods.get(i).getPriceNow()) {
//
//
//            }

        }


        RequestEntityMapSupply.putParameter("jointInfo", list);
        if (noJoinFlag) {
            RequestEntityMapSupply.putParameter("expireTime", expireTime.get(selectorposition));
        } else {
            RequestEntityMapSupply.putParameter("expireTime", "0");
        }

        request(RequestEntityMapSupply, AppSupplyRouterConstant.cmd_store_product_joint_updatePrice, onSubmitRequestListener);
    }

    OnRequestListener<StatusEntity> onSubmitRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            toast("网络问题,请点击重试");
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            toast(arg + "");//arg + ",请点击重试"
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();
            if (response != null) {
                DataManager.getInstance().clearPriceGoods();
                toast("提交成功");
                reqGoodsList(0);
                //finish();
            }
        }
    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            baseback.performClick();
        }
        return false;
    }

    private CustomDetailDeleteDialog deleteDialog;

    void back() {
        if (deleteDialog == null)
            deleteDialog = new CustomDetailDeleteDialog(this, true);
        deleteDialog.setMessage("确定放弃当前商品报价吗？");
        deleteDialog.setOnPositiveClickListener("确定", new CustomDetailDeleteDialog.onPositiveClickListener() {
            @Override
            public void onPositiveClickListener() {
                deleteDialog.dismiss();
                finish();
            }
        });
        deleteDialog.setOnNegativeClickListener("取消", new CustomDetailDeleteDialog.onNegativeClickListener() {
            @Override
            public void onNegativeClickListener() {
                deleteDialog.dismiss();
            }
        });
        deleteDialog.show();
    }

}
